package cn.springcloud.fix.common.starter.filter;

import cn.hutool.core.util.StrUtil;
import cn.springcloud.fix.common.core.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 租户过滤器
 */
@Slf4j
@ConditionalOnClass(Filter.class)
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //优先获取请求参数中的tenantId值
            String tenantId = request.getParameter(Constant.TENANT_ID);
            if (StrUtil.isEmpty(tenantId)) {
                tenantId = request.getHeader(Constant.TENANT_HEADER);
            }
            //保存租户id
            TenantContextHolder.setTenant(tenantId);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            TenantContextHolder.clear();
        }
    }
}
